<?php

class StatsController extends Controller {
    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array(
                'allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('count'),
                'users' => array('*'),
            ),
            array(
                'allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array(
                    'overview', 'customerajax', 'customerajax2', 
                    'guest', 'guestajax', 'hourajax', 'rangeajax',
                    'leave', 'leaveajax', 'leavehourajax', 'leaverangeajax',
                    'company', 'companyCountDay', 'companyCountYear', 'json_company', 'ajaxGateway'),
                'users' => array('@'),
            ),
            array(
                'allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'countDay', 'countYear', 'update', 'json_admin', 'countpage'),
                'users' => array('admin'),
            ),
            array(
                'deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
    * ================================================================================
    *  信息统计页面
    * ================================================================================
     */
    public function actionOverview(){ 
        if (Yii::app()->user->isGuest){
            throw new CHttpException(403,'请登录后使用这个功能.');
            return;
        }

        $companyid = Yii::app()->user->name=="admin" ? -1 : Yii::app()->user->id;

        $yesterday = date('Y-m-d', strtotime("- 1 day"));
        $beforeyesterday = date('Y-m-d', strtotime("$yesterday - 1 day"));
        
        $connection = Yii::app()->db;
        // 昨日路人
        $sql= 'select * from '.Customerstats::model()->tableName().' where createtime=\''.$yesterday.'\' and hour = -1 and companyid = '.$companyid;

        $result = $connection->createCommand($sql)->queryAll();

        foreach ($result as $row) {
             $model['today'] = ($row);
        }

        $sql= 'select * from '.Customerstats::model()->tableName().' where createtime=\''.$beforeyesterday.'\' and hour = -1 and companyid = '.$companyid;

        $result = $connection->createCommand($sql)->queryAll();

        foreach ($result as $row) {
             $model['yesterday'] = ($row);
        }

        $this->render('overview',array(
            'today'=>$model['today']  , 'yesterday' => $model['yesterday']
        ));
    }

    /**
    *   路人信息
    ***/
    public function actionGuest()
    { 
        if (Yii::app()->user->isGuest){
            throw new CHttpException(403,'请登录后使用这个功能.');
            return;
        }

        $companyid = Yii::app()->user->name=="admin" ? -1 : Yii::app()->user->id;

        $today = date("Y-m-d");
        $yesterday = date('Y-m-d', strtotime("$today - 1 day"));
        $beforeyesterday = date('Y-m-d', strtotime("$today - 2 day"));
        $week = $yesterday;

        $weekofday = '';// 本周其他的集合
        $lastweek = '';// 上周其他的集合

        // $week = date('Y-m-d', strtotime("$today - 1 week")); 
        while (ceil((strtotime($yesterday) - strtotime($week))/86400) < 7) {
            $weekofday =  $weekofday.',\''.$week.'\'';
            $week = date('Y-m-d', strtotime("$week - 1 day")); 
        }
        while (ceil((strtotime($yesterday) - strtotime($week))/86400) < 14) {
            $lastweek =  $lastweek.',\''.$week.'\'';
            $week = date('Y-m-d', strtotime("$week - 1 day")); 
        }
        // echo $yesterday;
        // echo "<br>";
        // echo $beforeyesterday;
        // echo "<br>";
        // echo "<br>";
        // echo $weekofday;
        // echo "<br>";
        // echo $lastweek;
        // return;

        $model['guests'] = 0;
        $model['guests2'] = 0;
        $model['avgweek'] = 0;
        $model['avgweek2'] = 0;
        $model['hourtop'] = 0;
        $model['hourtop2'] = 0;
        $model['weekavghour'] = 0;
        $model['weekavghour2'] = 0;


        $connection = Yii::app()->db;
        

        // 昨日路人
        $sql= 'select guests as guests from '.Customerstats::model()->tableName().' where createtime=\''.$yesterday.'\' and hour = -1 and companyid = '.$companyid;

        $result = $connection->createCommand($sql)->queryAll();

        foreach ($result as $row) {
             $model['guests'] = intval($row['guests']);
        }

        $sql= 'select guests as guests from '.Customerstats::model()->tableName().' where createtime=\''.$beforeyesterday.'\' and hour = -1 and companyid = '.$companyid;

        $result = $connection->createCommand($sql)->queryAll();

        foreach ($result as $row) {
             $model['guests2'] = intval($row['guests']);
        }



        // 一周路人平均数
        $sql='select avg(guests) as guests from '.Customerstats::model()->tableName().' where createtime in ('.substr($weekofday,1).') and hour = -1 and companyid = '.$companyid.'';

        $result = $connection->createCommand($sql)->queryAll();

        foreach ($result as $row) {
            $model['avgweek'] = intval($row['guests']);
        }  

        $sql='select avg(guests) as guests from '.Customerstats::model()->tableName().' where createtime in ('.substr($lastweek,1).') and hour = -1 and companyid = '.$companyid.'';

        $result = $connection->createCommand($sql)->queryAll();

        foreach ($result as $row) {
             $model['avgweek2'] = intval($row['guests']);
        }  
         
         
        // $avgweek = round($avgweek / 7);

        // 昨日路人最高
        $sql= 'select hour from '.Customerstats::model()->tableName().' where createtime=\''.$yesterday.'\' and hour != -1 and companyid = '.$companyid.' order by guests desc limit 1';
        $result = $connection->createCommand($sql)->queryAll();

        foreach ($result as $row) {
             $model['hourtop'] = intval($row['hour']);
        }

        $sql= 'select hour from '.Customerstats::model()->tableName().' where createtime=\''.$beforeyesterday.'\' and hour != -1 and companyid = '.$companyid.' order by guests desc limit 1';
        $result = $connection->createCommand($sql)->queryAll();

        foreach ($result as $row) {
             $model['hourtop2'] = intval($row['hour']);
        }

        // 周路人最高时段
        $sql='select avg(guests) as guests, hour from '.Customerstats::model()->tableName().' where createtime in ('.substr($weekofday,1).') and hour != -1 and companyid = '.$companyid.' group by hour order by guests desc limit 1';

        $result = $connection->createCommand($sql)->queryAll();

        foreach ($result as $row) {
            $model['weekavghour'] = intval($row['hour']);
        }


        $sql='select avg(guests) as guests, hour from '.Customerstats::model()->tableName().' where createtime in ('.substr($lastweek,1).') and hour != -1 and companyid = '.$companyid.' group by hour order by guests desc limit 1';

        $result = $connection->createCommand($sql)->queryAll();

        foreach ($result as $row) {
            $model['weekavghour2'] = intval($row['hour']);
        }
        
        // var_dump($model);
        // echo $guests . '||'. $avgweek. '||'. $hourtop. '||'. $weekavghour ; 

        // return;
        $this->render('guest',array(
            'model'=>$model
        ));
    }

    /**
    *   流失顾客信息
    ***/
    public function actionLeave()
    { 
        if (Yii::app()->user->isGuest){
            throw new CHttpException(403,'请登录后使用这个功能.');
            return;
        }

        $companyid = Yii::app()->user->name=="admin" ? -1 : Yii::app()->user->id;

        $today = date("Y-m-d");
        $yesterday = date('Y-m-d', strtotime("$today - 1 day"));
        $beforeyesterday = date('Y-m-d', strtotime("$today - 2 day"));
        $week = $yesterday;

        $weekofday = '';// 本周其他的集合
        $lastweek = '';// 上周其他的集合

        // $week = date('Y-m-d', strtotime("$today - 1 week")); 
        while (ceil((strtotime($yesterday) - strtotime($week))/86400) < 7) {
            $weekofday =  $weekofday.',\''.$week.'\'';
            $week = date('Y-m-d', strtotime("$week - 1 day")); 
        }
        while (ceil((strtotime($yesterday) - strtotime($week))/86400) < 14) {
            $lastweek =  $lastweek.',\''.$week.'\'';
            $week = date('Y-m-d', strtotime("$week - 1 day")); 
        }
        // echo $yesterday;
        // echo "<br>";
        // echo $beforeyesterday;
        // echo "<br>";
        // echo "<br>";
        // echo $weekofday;
        // echo "<br>";
        // echo $lastweek;
        // return;

        $model['leave'] = 0;
        $model['leave2'] = 0;
        $model['avgweek'] = 0;
        $model['avgweek2'] = 0;
        $model['hourtop'] = 0;
        $model['hourtop2'] = 0;
        $model['weekavghour'] = 0;
        $model['weekavghour2'] = 0;


        $connection = Yii::app()->db;
        

        // 昨日路人
        $sql= 'select `leave` from '.Customerstats::model()->tableName().' where createtime=\''.$yesterday.'\' and hour = -1 and companyid = '.$companyid;

        $result = $connection->createCommand($sql)->queryAll();

        foreach ($result as $row) {
             $model['leave'] = intval($row['leave']);
        }
        // echo $sql;
        // var_dump($model);
        // return;

        $sql= 'select `leave` from '.Customerstats::model()->tableName().' where createtime=\''.$beforeyesterday.'\' and hour = -1 and companyid = '.$companyid;

        $result = $connection->createCommand($sql)->queryAll();

        foreach ($result as $row) {
             $model['leave2'] = intval($row['leave']);
        }



        // 一周路人平均数
        $sql='select avg(`leave`) as leaves from '.Customerstats::model()->tableName().' where createtime in ('.substr($weekofday,1).') and hour = -1 and companyid = '.$companyid.'';

        $result = $connection->createCommand($sql)->queryAll();

        foreach ($result as $row) {
            $model['avgweek'] = intval($row['leaves']);
        }  

        $sql='select avg(`leave`) as leaves from '.Customerstats::model()->tableName().' where createtime in ('.substr($lastweek,1).') and hour = -1 and companyid = '.$companyid.'';

        $result = $connection->createCommand($sql)->queryAll();

        foreach ($result as $row) {
             $model['avgweek2'] = intval($row['leaves']);
        }  
         
         
        // $avgweek = round($avgweek / 7);

        // 昨日路人最高
        $sql= 'select hour from '.Customerstats::model()->tableName().' where createtime=\''.$yesterday.'\' and hour != -1 and companyid = '.$companyid.' order by `leave` desc limit 1';
        $result = $connection->createCommand($sql)->queryAll();

        foreach ($result as $row) {
             $model['hourtop'] = intval($row['hour']);
        }

        $sql= 'select hour from '.Customerstats::model()->tableName().' where createtime=\''.$beforeyesterday.'\' and hour != -1 and companyid = '.$companyid.' order by `leave` desc limit 1';
        $result = $connection->createCommand($sql)->queryAll();

        foreach ($result as $row) {
             $model['hourtop2'] = intval($row['hour']);
        }

        // 周路人最高时段
        $sql='select avg(`leave`) as leaves, hour from '.Customerstats::model()->tableName().' where createtime in ('.substr($weekofday,1).') and hour != -1 and companyid = '.$companyid.' group by hour order by leaves desc limit 1';

        $result = $connection->createCommand($sql)->queryAll();

        foreach ($result as $row) {
            $model['weekavghour'] = intval($row['hour']);
        }


        $sql='select avg(`leave`) as leaves, hour from '.Customerstats::model()->tableName().' where createtime in ('.substr($lastweek,1).') and hour != -1 and companyid = '.$companyid.' group by hour order by leaves desc limit 1';

        $result = $connection->createCommand($sql)->queryAll();

        foreach ($result as $row) {
            $model['weekavghour2'] = intval($row['hour']);
        }
        

        // var_dump(json_encode($model));
        // return;
        $this->render('leave',array(
            'model'=>$model
        ));
    }

    /**
    * 路人每天统计
    **/
    public function actionGuestajax($s , $e){
        header('Content-type: application/json;charset=utf-8');

        if (Yii::app()->user->isGuest){
            throw new CHttpException(403,'请登录后使用这个功能.');
            return;
        }

        $companyid = Yii::app()->user->name=="admin" ? -1 : Yii::app()->user->id;

        $total = 20;

        $start = date('Y-m-d', strtotime("$s"));
        $end = $e == '0'? date('Y-m-d', strtotime("-1 day")) : date('Y-m-d', strtotime("$e"));

        // echo $start .'|'.$end;
        // return;

        $days = ceil((strtotime($end) - strtotime($start))/86400); 
        if ($days < 1) {
            echo json_encode(array('code' => 1000,  'message' => "开始日期大于截止日期，请重试"));
            return ;
        }

        $scope = '';
        $step = intval($days / $total);
        $step = $step == 0 ? 1 : $step;
        $i = 0;
        // return ;
        while ( 0 < ceil((strtotime($end) - strtotime($start))/86400) && $i <= $total){
            $scope =  $scope.',\''.$end.'\'';
            $end = date('Y-m-d', strtotime("$end - ".$step." day"));
            $i++;
        }

        // echo $scope .'|'.$days;
        // return;

        // 昨日路人
        $sql= 'select guests , createtime from '.Customerstats::model()->tableName().' where createtime in ('.substr($scope,1).')  and hour = -1 and companyid = '.$companyid .' order by id asc';

        $connection = Yii::app()->db;
        $result = $connection->createCommand($sql)->queryAll();

        $values = array();
        $dates = array();
        foreach ($result as $value) {
            $values[] = intval($value['guests']);
            $dates[] = substr($value['createtime'] , 5);
        }

        if ((count($result) % 2) == 1) {
            $result[] = array('createtime'=>'&nbsp;' , 'guests' => '&nbsp;');
        }

        echo json_encode(array('value'=>$values , 'date' => $dates , 'list' => $result ));
        
    } 
    /**
    * 路人小时
    **/
    public function actionHourajax($s ){
        header('Content-type: application/json;charset=utf-8');

        if (Yii::app()->user->isGuest){
            throw new CHttpException(403,'请登录后使用这个功能.');
            return;
        }

        $companyid = Yii::app()->user->name=="admin" ? -1 : Yii::app()->user->id;


        $start = $s == '0'? date('Y-m-d', strtotime("-1 day")) : date('Y-m-d', strtotime("$s"));

        // 昨日路人
        $sql= 'select guests , hour from '.Customerstats::model()->tableName().' where createtime = \''.$start.'\' and hour != -1 and companyid = '.$companyid .' order by hour asc';

        $connection = Yii::app()->db;
        $result = $connection->createCommand($sql)->queryAll();

        $values = array();
        $dates = array();
        $hours = array();
        foreach ($result as $value) {
            $values[] = intval($value['guests']);
            $dates[] = $value['hour'];
            $hours[] = array('guests'=> $value['guests'], 'hour'=> $start." ".$value['hour'].'时');
        }

        if ((count($result) % 2) == 1) {
            $result[] = array('hour'=>'&nbsp;' , 'guests' => '&nbsp;');
        }

        echo json_encode(array('value'=>$values , 'date' => $dates , 'list' => $hours ));
        
    } 
    /**
    *   路人月范围统计
    **/
    function actionRangeajax(){
        header('Content-type: application/json;charset=utf-8');

        if (Yii::app()->user->isGuest){
            throw new CHttpException(403,'请登录后使用这个功能.');
            return;
        }

        $companyid = Yii::app()->user->name=="admin" ? -1 : Yii::app()->user->id;


        $start = date('Y-m-d', strtotime("-1 year"));


        // 昨日路人
        $sql= 'select sum(guests) as guests ,substring(createtime, 1 , 7) as month from '.Customerstats::model()->tableName().' where str_to_date(createtime , \'%Y-%m-%d\') > \''.$start.'\' and hour != -1 and companyid = '.$companyid .' group by month';

        $connection = Yii::app()->db;
        $result = $connection->createCommand($sql)->queryAll();

        $values = array();
        $dates = array();
        // $hours = array();
        foreach ($result as $value) {
            $values[] = intval($value['guests']);
            $dates[] = $value['month'];
            // $hours[] = array('guests'=> $value['guests'], 'hour'=> $start." ".$value['hour'].'时');
        }

        if ((count($result) % 2) == 1) {
            $result[] = array('month'=>'&nbsp;' , 'guests' => '&nbsp;');
        }

        echo json_encode(array('value'=>$values , 'date' => $dates , 'list' => $result ));
        
    } 
      
    /**
    * 路人每天统计
    **/
    public function actionCustomerajax($s , $e){
        header('Content-type: application/json;charset=utf-8');

        if (Yii::app()->user->isGuest){
            throw new CHttpException(403,'请登录后使用这个功能.');
            return;
        }

        $companyid = Yii::app()->user->name=="admin" ? -1 : Yii::app()->user->id;

        $total = 20;

        $start = date('Y-m-d', strtotime("$s"));
        $end = $e == '0'? date('Y-m-d', strtotime("-1 day")) : date('Y-m-d', strtotime("$e"));

        // echo $start .'|'.$end;
        // return;

        $days = ceil((strtotime($end) - strtotime($start))/86400); 
        if ($days < 1) {
            echo json_encode(array('code' => 1000,  'message' => "开始日期大于截止日期，请重试"));
            return ;
        }

        $scope = '';
        $step = intval($days / $total);
        $step = $step == 0 ? 1 : $step;
        $i = 0;
        // return ;
        while ( 0 < ceil((strtotime($end) - strtotime($start))/86400) && $i <= $total){
            $scope =  $scope.',\''.$end.'\'';
            $end = date('Y-m-d', strtotime("$end - ".$step." day"));
            $i++;
        }

        // echo $scope .'|'.$days;
        // return;

        // 昨日路人
        $sql= 'select newbie , regular , createtime from '.Customerstats::model()->tableName().' where createtime in ('.substr($scope,1).')  and hour = -1 and companyid = '.$companyid .' order by id asc';

        $connection = Yii::app()->db;
        $result = $connection->createCommand($sql)->queryAll();

        $newbie = array();
        $regular = array();
        $dates = array();
        foreach ($result as $value) {
            $regular[] = intval($value['regular']);
            $newbie[] = intval($value['newbie']);
            $dates[] = substr($value['createtime'] , 5);
        }

        if ((count($result) % 2) == 1) {
            $result[] = array('createtime'=>'&nbsp;' , 'newbie' => '&nbsp;', 'regular' => '&nbsp;');
        }

        echo json_encode(array('regular'=>$regular ,'newbie'=>$newbie , 'date' => $dates , 'list' => $result ));
        
    } 

    /**
    * 路人小时
    **/
    public function actionCustomerajax2($s ){
        // header('Content-type: application/json;charset=utf-8');

        if (Yii::app()->user->isGuest){
            throw new CHttpException(403,'请登录后使用这个功能.');
            return;
        }

        $companyid = Yii::app()->user->name=="admin" ? -1 : Yii::app()->user->id;


        $start = $s == '0'? date('Y-m-d', strtotime("-1 day")) : date('Y-m-d', strtotime("$s"));

        // 昨日路人
        $sql= 'select newbie , regular , guests , `leave` , customer , hour from '.Customerstats::model()->tableName().' where createtime = \''.$start.'\' and companyid = '.$companyid .' order by hour asc';

        $connection = Yii::app()->db;
        $result = $connection->createCommand($sql)->queryAll();

        $newbie = array();
        $regular = array();
        $dates = array();
        $hours = array();
        $days = array();
        foreach ($result as $value) {
            if (intval($value['hour']) == -1) {
                $days[] = array( 'name'=>'路人数' , 'y'=> intval($value['guests']) );
                $days[] = array( 'name'=>'进店顾客数' , 'y'=> intval($value['customer']) );
                $days[] = array( 'name'=>'流失顾客数' , 'y'=> intval($value['leave']) );
            }else{

            $newbie[] = intval($value['newbie']);
            $regular[] = intval($value['regular']);
            $dates[] = $value['hour'];
            $hours[] = array('regular'=> $value['regular'],'newbie'=> $value['newbie'], 'hour'=> $start." ".$value['hour'].'时');
            }
        }

        if ((count($result) % 2) == 1) {
            $result[] = array('hour'=>'&nbsp;' , 'regular' => '&nbsp;', 'newbie' => '&nbsp;');
        }

        echo json_encode(array('newbie'=>$newbie , 'regular'=>$regular , 'date' => $dates , 'list' => $hours , 'pie'=> $days) );
        
    } 



    /**
    * 路人每天统计
    **/
    public function actionLeaveajax($s , $e){
        header('Content-type: application/json;charset=utf-8');

        if (Yii::app()->user->isGuest){
            throw new CHttpException(403,'请登录后使用这个功能.');
            return;
        }

        $companyid = Yii::app()->user->name=="admin" ? -1 : Yii::app()->user->id;

        $total = 20;

        $start = date('Y-m-d', strtotime("$s"));
        $end = $e == '0'? date('Y-m-d', strtotime("-1 day")) : date('Y-m-d', strtotime("$e"));

        // echo $start .'|'.$end;
        // return;

        $days = ceil((strtotime($end) - strtotime($start))/86400); 
        if ($days < 1) {
            echo json_encode(array('code' => 1000,  'message' => "开始日期大于截止日期，请重试"));
            return ;
        }

        $scope = '';
        $step = intval($days / $total);
        $step = $step == 0 ? 1 : $step;
        $i = 0;
        // return ;
        while ( 0 < ceil((strtotime($end) - strtotime($start))/86400) && $i <= $total){
            $scope =  $scope.',\''.$end.'\'';
            $end = date('Y-m-d', strtotime("$end - ".$step." day"));
            $i++;
        }

        // echo $scope .'|'.$days;
        // return;

        // 昨日路人
        $sql= 'select `leave` , createtime from '.Customerstats::model()->tableName().' where createtime in ('.substr($scope,1).')  and hour = -1 and companyid = '.$companyid .' order by id asc';

        $connection = Yii::app()->db;
        $result = $connection->createCommand($sql)->queryAll();

        $values = array();
        $dates = array();
        foreach ($result as $value) {
            $values[] = intval($value['leave']);
            $dates[] = substr($value['createtime'] , 5);
        }

        if ((count($result) % 2) == 1) {
            $result[] = array('createtime'=>'&nbsp;' , 'leave' => '&nbsp;');
        }

        echo json_encode(array('value'=>$values , 'date' => $dates , 'list' => $result ));
        
    } 
    /**
    * 路人小时
    **/
    public function actionLeavehourajax($s ){
        // header('Content-type: application/json;charset=utf-8');

        if (Yii::app()->user->isGuest){
            throw new CHttpException(403,'请登录后使用这个功能.');
            return;
        }

        $companyid = Yii::app()->user->name=="admin" ? -1 : Yii::app()->user->id;


        $start = $s == '0'? date('Y-m-d', strtotime("-1 day")) : date('Y-m-d', strtotime("$s"));

        // 昨日路人
        $sql= 'select `leave` , hour from '.Customerstats::model()->tableName().' where createtime = \''.$start.'\' and hour != -1 and companyid = '.$companyid .' order by hour asc';

        $connection = Yii::app()->db;
        $result = $connection->createCommand($sql)->queryAll();

        $values = array();
        $dates = array();
        $hours = array();
        foreach ($result as $value) {
            $values[] = intval($value['leave']);
            $dates[] = $value['hour'];
            $hours[] = array('guests'=> $value['leave'], 'hour'=> $start." ".$value['hour'].'时');
        }

        if ((count($result) % 2) == 1) {
            $result[] = array('hour'=>'&nbsp;' , 'leave' => '&nbsp;');
        }

        echo json_encode(array('value'=>$values , 'date' => $dates , 'list' => $hours ));
        
    } 
    /**
    *   路人月范围统计
    **/
    function actionLeaverangeajax(){
        header('Content-type: application/json;charset=utf-8');

        if (Yii::app()->user->isGuest){
            throw new CHttpException(403,'请登录后使用这个功能.');
            return;
        }

        $companyid = Yii::app()->user->name=="admin" ? -1 : Yii::app()->user->id;


        $start = date('Y-m-d', strtotime("-1 year"));


        // 昨日路人
        $sql= 'select sum(guests) as guests ,substring(createtime, 1 , 7) as month from '.Customerstats::model()->tableName().' where str_to_date(createtime , \'%Y-%m-%d\') > \''.$start.'\' and hour != -1 and companyid = '.$companyid .' group by month';

        $connection = Yii::app()->db;
        $result = $connection->createCommand($sql)->queryAll();

        $values = array();
        $dates = array();
        // $hours = array();
        foreach ($result as $value) {
            $values[] = intval($value['guests']);
            $dates[] = $value['month'];
            // $hours[] = array('guests'=> $value['guests'], 'hour'=> $start." ".$value['hour'].'时');
        }

        if ((count($result) % 2) == 1) {
            $result[] = array('month'=>'&nbsp;' , 'guests' => '&nbsp;');
        }

        echo json_encode(array('value'=>$values , 'date' => $dates , 'list' => $result ));
        
    } 
    /**
     * 页面上手动统计
     **/ 
    public function actionCountpage(){ 
         
        $this->render('countpage');
        
    }
    /**
     * ====================================================================================
     * ====================================================================================
     * 统计插入到数据库中
     *    默认是统计当天时间的前一天数据。
     *    如果传递要统计的天数，则统计不包含当天的前数据,数据库存在则删除后插入
     * 1、统计超级管理员关注的信息，一天一条
     * 2、统计每一个企业的关注的信息，一天一个企业一条
     * 3、统计每一个路由器关注的信息，一天一个路由一条 
     * ====================================================================================
     * ====================================================================================
     **/
    public function actionCount() {
        header('Content-type: text/html;charset=utf-8');


        if (empty($_GET['day'])) {
            
            // $start = date("Y-m-d");

            $start = date('Y-m-d', strtotime("- 1 day"));  
            $this->analyze($start);

            //统计路由器
            // $this->totalCountGateway($start, "%Y-%m-%d"); 

            // $this->totalCountGateway(date('Y-m', strtotime($start)) , "%Y-%m"); 
            //统计企业
            // $this->totalCountCompany($start, "%Y-%m-%d"); 

            // $this->totalCountCompany(date('Y-m', strtotime($start)) , "%Y-%m"); 
            // //统计管理员
            // $this->totalCountAdmin($start, "%Y-%m-%d"); 

            // $this->totalCountAdmin(date('Y-m', strtotime($start)) , "%Y-%m");  
            
            echo '<br>统计昨天数据完成。'; 
            echo "<script> window.parent.resetButton();</script>";
        }else{
            $start = $_GET['day'];  

            $end = date('Y-m-d', strtotime("- 1 day")); 

            $days = ceil((strtotime($end) - strtotime($start))/86400);  

            if ( 0 > $days) {
                echo "统计完成！";
                echo "<script> window.parent.resetButton();</script>";
                exit;
            } 
            echo "正在统计数据，请稍等...<br>";
            $this->analyze($start);

             //统计路由器
            // $this->totalCountGateway($start, "%Y-%m-%d"); 

            // $this->totalCountGateway(date('Y-m', strtotime($start)) , "%Y-%m"); 

            //统计企业
            // $this->totalCountCompany($start, "%Y-%m-%d"); 

            // $this->totalCountCompany(date('Y-m', strtotime($start)) , "%Y-%m");  
            
            // // //统计系统管理员
            // $this->totalCountAdmin($start , "%Y-%m-%d");

            // $this->totalCountAdmin(date('Y-m', strtotime($start)) , "%Y-%m"); 

            // 跳转下一天的统计
            $start = date('Y-m-d', strtotime("$start + 1 day")); 
            echo "<meta http-equiv='refresh' content='0; url=".$this->createUrl('count',array('day'=>$start))."'>";
        }
        exit;   
    }
    /**
    *
    *
    **/
    private function analyze($day){

        $connection = Yii::app()->db;
        $sql = "select id from ".Company::model()->tableName();
        $result = $connection->createCommand($sql)->queryAll();
        array_push($result , array('id'=> -1));
        // var_dump($result);
        echo '正在计算'.$day.'的数据...<br>' ;
        foreach ($result as $row) {
            echo ($row['id']);
            echo "<br>";
            $this->analyzeGuest($day, intval($row['id']));

        }
    }
    /**
    *
    */
    private function analyzeGuest($datestr , $companyid){
        $connection = Yii::app()->db;

        $where = $companyid > -1 ? ' companyid = '.$companyid.' and ' : "";
        // 清除统计中之前的数据

        $sql="delete from ".Customerstats::model()->tableName()." where companyid = ".$companyid." and createtime = '".$datestr."'";

        $result = $connection->createCommand($sql)->execute();
        
        $dayData['guests'] = 0;
        $dayData['customer'] = 0;
        $dayData['newbie'] = 0;
        $dayData['regular'] = 0;
        $dayData['leaves'] = 0;
           
        for ($i=0; $i < 24; $i++) {
                
            $hour = $i > 9 ? $datestr.' '.$i : $datestr.' 0'.$i;

            $sql="select count(id) as guests from ".Linklog::model()->tableName()." where ".$where." date_format(createtime,'%Y-%m-%d %H') = '".$hour."'";
            
            $result = $connection->createCommand($sql)->queryAll();

            foreach ($result as $row) {
                $saveData['guests']=intval($row['guests']);
            }

            $sql="select count(DISTINCT userid) as customer from ".Connectionlog::model()->tableName()." where ".$where." date_format(createtime,'%Y-%m-%d %H') = '".$hour."'";

            $result = $connection->createCommand($sql)->queryAll();

            foreach ($result as $row) {
                $saveData['customer']=intval($row['customer']);
            }
            
            $sql="select count(id) as newbie from ".CompanyUser::model()->tableName()." where ".$where." date_format(createtime,'%Y-%m-%d %H') = '".$hour."'";

            $result = $connection->createCommand($sql)->queryAll();

            foreach ($result as $row) {
                $saveData['newbie']=intval($row['newbie']);
            }


            $saveData['leave'] = $saveData['guests'] - $saveData['customer'];
            $saveData['regular'] = $saveData['customer'] - $saveData['newbie'];

       
            $customer = new Customerstats();
            $customer->createtime = $datestr;
            $customer->companyid = $companyid;
            $customer->hour = $i;
 
            $customer->guests = $saveData["guests"];
            $customer->customer = $saveData["customer"];
            $customer->newbie = $saveData['newbie'];
            $customer->regular = $saveData["regular"];
            $customer->leave = $saveData["leave"];


            $customer->save(); 


            $dayData['guests'] += intval($saveData["guests"]);
            $dayData['customer']  += intval($saveData["customer"]);
            $dayData['newbie']  += intval($saveData["newbie"]);
            $dayData['regular']  += intval($saveData["regular"]);
            $dayData['leaves']  += intval($saveData["leave"]);

            // echo "<pre>";
            // var_dump($saveData);
            // echo "</pre>";
        }

        $customer = new Customerstats();
        $customer->createtime = $datestr;
        $customer->companyid = $companyid;
        $customer->hour = -1;

        $customer->guests = intval($dayData['guests']);
        $customer->customer = intval($dayData['customer']);
        $customer->newbie = intval($dayData['newbie']);
        $customer->regular = intval($dayData['regular']);
        $customer->leave = intval($dayData['leaves']);

        $customer->save();
        


        echo "<br>";
    }
   
}
